package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.SysCourse;
import com.ruoyi.common.enums.CourseStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysCourseMapper;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.system.service.ISysCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import java.util.List;


@Service
public class SysCourseServiceImpl implements ISysCourseService {

    @Autowired
    private SysCourseMapper sysCourseMapper;

    @Autowired
    private IAppUserService appUserService;

    @Override
    public List<SysCourse> getSysCourseList(SysCourse sysCourse) {
        return sysCourseMapper.selectCourseList(sysCourse);
    }

    @Override
    public SysCourse getSysCourseById(Long courseId) {
        return sysCourseMapper.selectById(courseId);
    }

    @Override
    public int insertCourse(SysCourse sysCourse) {
        Long userId = sysCourse.getUserId();
        // 根据用户查询用户姓名
        AppUser appUser = appUserService.selectUserById(userId);
        sysCourse.setNickName(appUser.getNickName());
        sysCourse.setCurrentNumber(sysCourse.getNumberChange());
        return sysCourseMapper.insert(sysCourse);
    }

    @Override
    public int updateCourse(SysCourse sysCourse) {
        //根据curseId获取详细课程
        SysCourse oldSysCourse = sysCourseMapper.selectById(sysCourse.getCourseId());
        Integer newNumberChange = sysCourse.getNumberChange();
        Integer oldNumberChange = oldSysCourse.getNumberChange();
        Integer result =  newNumberChange - oldNumberChange;
        // 重新更新当前课程数
        sysCourse.setCurrentNumber(oldSysCourse.getCurrentNumber() + result);
        return sysCourseMapper.update(sysCourse);
    }


    @Override
    public int delete(Long curseId) {
        return sysCourseMapper.deleteById(curseId);
    }

    @Override
    public int activated(Long curseId) {
        SysCourse sysCourse = sysCourseMapper.selectById(curseId);
        sysCourse.setCourseStatus(CourseStatus.ACTIVATED.getCode());
        sysCourse.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        return sysCourseMapper.update(sysCourse);
    }
}
